package com.action.wx.product;

import com.common.BaseAction;
import com.common.ModelAndJson;
import com.common.SystemConfig;
import com.github.pagehelper.Page;
import com.service.product.ProductService;
import com.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
@RequestMapping("wx/product")
public class WxProductAction extends BaseAction {
    @Autowired
    private ProductService productService;

    @RequestMapping("list")
    public ModelAndView goList(Integer cid, Integer pageNum, String keyword) {
        pageNum = pageNum == null ? 1 : pageNum;
        int pageSize = Config.getInt("page.pageSize");
        HashMap<String, Object> paraMap = new HashMap<>();
        ModelMap modelMap = new ModelMap();
        HttpSession session = this.getSession();
        Integer cityId = (Integer) session.getAttribute(SystemConfig.CityIdSession);
        if (cid == null && cityId == null) {
            return new ModelAndView("redirect:/wx/index.htm", modelMap);
        }
        cid = cid == null ? cityId : cid;
        paraMap.put("cityId", cid);
        paraMap.put("keyword", keyword);
        Page result = productService.findByPage(pageNum, pageSize, paraMap);
        modelMap.put("cid", cid);
        modelMap.put("keyword", keyword);
        modelMap.put("page", result);
        modelMap.put("totalPage", result.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        return new ModelAndView("/wx/product/list", modelMap);
    }

    @ResponseBody
    @RequestMapping("listData")
    public String listData(ModelAndJson modelMap, Integer cid, Integer pageNum, Integer pageSize, String keyword) {
        pageNum = pageNum == null ? 1 : pageNum;
        HashMap<String, Object> paraMap = new HashMap<>();
        paraMap.put("cityId", cid);
        paraMap.put("keyword", keyword);
        Page result = productService.findByPage(pageNum, pageSize, paraMap);
        modelMap.put("cid", cid);
        modelMap.put("page", result);
        modelMap.put("totalPage", result.getPages());
        modelMap.put("pageNum", pageNum);
        modelMap.put("pageSize", pageSize);
        return modelMap.toString();
    }
}
